package stz.flash.main.flashlight.model;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.decor.Background;
import net.rim.device.api.ui.decor.BackgroundFactory;
import stz.flash.main.flashlight.field.FontColor;
import stz.flash.option.flashlight.BacklightOption;
import util.DjObservable;
import util.DjObserver;
import blackberry.util.image.DjImageResizer;


public class BacklightFieldChangeListener implements DjObserver {
	
	private static final String IMAGE_BACKGROUND_BRIGHT = "Flashlight_Background_Bright.jpg";
	private static final String IMAGE_BACKGROUND_DARK = "Flashlight_Background_Dark.jpg";
	
	private static Background brightBackground;
	private static Background darkBackground;
	
	private Manager flashManager;

	public BacklightFieldChangeListener(Manager flashManger) {
		this.flashManager = flashManger;
		getBacklightOption().updateLatestBacklightStateWithStartupSet();
		getBacklightOption().addObserver(this);
		update(getBacklightOption(), null);	
	}
	
	public void update(DjObservable observable, Object obj) {
		setBackground();
	}
	
	private void setBackground(){
		if (getBacklightOption().isLatestBacklightState()){
//			if (brightBackground == null) 
//				brightBackground = getBrightBackground();
			setBitmapBackground(brightBackground);
			
			FontColor.setFontColor(FontColor.COLOR_DARK);
			
		} else {
			
			if (darkBackground == null) 
				darkBackground = getDarkBackground();
			setBitmapBackground(darkBackground);
			FontColor.setFontColor(FontColor.COLOR_BRIGHT);
		}
	}
	private void setBitmapBackground(Background background) {
		flashManager.setBackground(background);
	}
	
	private Background getBrightBackground() { 
		return BackgroundFactory.createBitmapBackground(
				DjImageResizer.fillIntoDisplay(
						getBrightBitmapResource(), 
						480, 800, 480, 800,
						Field.FIELD_TOP, Bitmap.FILTER_BILINEAR));
	}
	private Bitmap getBrightBitmapResource(){
		return Bitmap.getBitmapResource(IMAGE_BACKGROUND_BRIGHT);
	}
	
	private Background getDarkBackground() { 
		return BackgroundFactory.createBitmapBackground(
				DjImageResizer.fillIntoDisplay(
						getDarkBitmapResource(), 
						480, 800, 480, 800,
						Field.FIELD_TOP, Bitmap.FILTER_BILINEAR));
	}
	private Bitmap getDarkBitmapResource(){
		return Bitmap.getBitmapResource(IMAGE_BACKGROUND_DARK);
	}
	
	private BacklightOption getBacklightOption() {
		return BacklightOption.getIns();
	}
}